package database

import (
	"context"

	"gitee.com/xchengli/blog-lib/config"

	"github.com/redis/go-redis/v9"
)

// Redis连接池大小
var MAX_POOL_SIZE = 20
var RedisPoll chan *redis.Client
var RedisConn *redis.Client

func ConnRedis(network, address string) *redis.Client {
	// 缓冲机制，相当于消息队列
	if len(RedisPoll) == 0 {
		// 如果长度为0，就定义一个redis.Conn类型长度为MAX_POOL_SIZE的channel
		RedisPoll = make(chan *redis.Client, MAX_POOL_SIZE)
		go func() {
			for i := 0; i < MAX_POOL_SIZE/2; i++ {
				c := redis.NewClient(&redis.Options{
					Addr:     config.RedisConf.Address,
					Password: config.RedisConf.Password,
					DB:       config.RedisConf.DB,
				})
				// 测试连接
				ctx := context.Background()
				_, err := c.Ping(ctx).Result()
				if err != nil {
					panic(err)
				}
				putRedis(c)
			}
		}()
	}
	return <-RedisPoll
}

func putRedis(conn *redis.Client) {
	// 基于函数和接口间互不信任原则，这里再判断一次，养成这个好习惯
	if RedisPoll == nil {
		RedisPoll = make(chan *redis.Client, MAX_POOL_SIZE)
	}
	if len(RedisPoll) >= MAX_POOL_SIZE {
		conn.Close()
		conn = nil
		return
	}
	RedisPoll <- conn
}

func InitRedis() {
	if RedisConn == nil {
		RedisConn = ConnRedis(config.RedisConf.Network, config.RedisConf.Address)
	}

	ctx := context.Background()

	// 测试连接
	_, err := RedisConn.Ping(ctx).Result()
	if err != nil {
		panic(err)
	}
}
